<template>
  <BasicDrawer 
    ref="drawerRef"
    v-bind="$attrs" 
    @register="registerDrawer" 
    :title="title" 
    width="1000px" 
    destroyOnClose 
    showFooter 
    @ok="handleSubmit"
  >
    <MyAlert 
      type="warning" 
      message="目前接口授权会查询系统中所有接口资源, 为了避免安全问题, 最好只有平台租户(后台管理)才能拥有此权限"
    />

    <Spin :spinning="state.loading">
      <Transfer
        v-model:target-keys="stateValue.targetKeys"
        :data-source="stateValue.dataSource"
        show-search
        :list-style="{
          width: '90%',
          minWidth: '300px',
          height: 'calc(100vh - 300px)',
        }"
        :render="item => `${item.title} ${item.actions}`"
        :pagination="state.pagination"
        @search="handleSearch"
        @change="handleChange"
      >
        <template #footer="{ direction }">
          <div :class="`${prefixCls}-action-type`">
            <JDictSelectTag 
              v-if="direction === 'left'" 
              :placeholder="'操作类型'" 
              :dictCode="state.actionTypeDict"
              @change="handleActionTypeChange"
            />
          </div>
        </template>
        <template #notFoundContent>
          <Empty class="!mt-4"/>
        </template>
      </Transfer>
    </Spin>
  </BasicDrawer>
</template>
<script lang="ts" setup>
import { Empty, Spin, Transfer } from 'ant-design-vue';
import { ref, computed, unref, onUnmounted, onMounted, toRaw } from 'vue';
import { BasicDrawer, useDrawer, useDrawerInner } from '/@/components/Drawer';
import { listResource, type RamResource } from '/@/views/ram/resource/resource.api'
import { useDesign } from '/@/hooks/web/useDesign';
import { PopConfirmButton } from '/@/components/Button';
import { isArray, isFunction } from '/@/utils/is';
import { formRolePermissionSchema } from '../role.data';
import { listApiResource, saveApiResource } from '/@/api/sys/role';
import { useMessage } from '/@/hooks/web/useMessage';
import { JDictSelectTag } from '/@/components/Form';
 import MyAlert from '/@/components/My/MyAlert.vue';

const { createMessage } = useMessage();

const emit = defineEmits(['success', 'register']);
const { prefixCls } = useDesign('role-api-perm');

interface DataSource {
  key: string;
  title: string;
  actionType: string;
  actions: string;
  chosen: boolean;
}

interface State {
  // 树的全部节点信息
  allTreeKeys: any[];
  //树的选择节点信息
  checkedKeys: any[];
  halfCheckedKeys: any[];
  defaultCheckedKeys: any[];

  resourceList: RamResource[];
  targetKeys: string[];
  dataSource: DataSource[];
  actionTypeDict: string;
  actionType?: string;
  loading?: boolean;
  timer?: any;
  roleId: string;
  pagination: any;
  record: any
}

const state = ref<State>({
  allTreeKeys: [],
  checkedKeys: [],
  halfCheckedKeys: [],
  defaultCheckedKeys: [],

  resourceList: [],
  targetKeys: [],
  dataSource: [],
  loading: false,
  actionTypeDict: 'ram_resource_action_type',
  roleId: '',
  pagination: {
    pageSize: 20
  },
  record: {}
})
const stateValue = state.value
const drawerRef = ref<HTMLElement>()
const title = computed(() => `接口授权 【${state.value.record.roleName}】`)
onMounted(() => {

})

const handleChange = (keys: string[], direction: string, moveKeys: string[]) => {
  if (direction === 'right') {
    stateValue.targetKeys = keys
  }
};

const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  setDrawerProps({ confirmLoading: false, loading: true });
  try {
    stateValue.roleId = data.record.id
    stateValue.record = data.record
    const permList = await listApiResource({roleId: stateValue.roleId})
    stateValue.targetKeys = permList ? permList.map(e => e.action + '_' + e.name) : []
    stateValue.resourceList = await listResource({}) as RamResource[]
    stateValue.dataSource = stateValue.resourceList.map(e => ({
      key: e.action + '_' + e.name,
      title: e.name,
      actionType: e.actionType,
      url: e.url,
      actions: e.action,
      chosen: Math.random() * 2 > 1,
    }))
  } finally {
    setDrawerProps({ loading: false });
  }
});

onUnmounted(() => {
  clearTimeout(stateValue.timer)
})

const handleActionTypeChange = async (value) => {
  if (isArray(value)) {
    return
  }
  stateValue.actionType = value
  console.log('actionType: ', value);
  try {
    stateValue.dataSource = stateValue.resourceList.filter(e => !value || e.actionType === value)
      .map((e) => ({
        key: e.action + '_' + e.name,
        title: e.name,
        actionType: e.actionType,
        actions: e.action,
        chosen: Math.random() * 2 > 1,
      }))
  } finally {

  }
}

const handleSearch = () => {

}

const handleSubmit = async () => {
  setDrawerProps({confirmLoading: true});
  try {
    const actionList = toRaw(stateValue.targetKeys).map(e => e.split('_')[0])
    await saveApiResource({ subjectId: stateValue.roleId, actionList})
    createMessage.success('授权成功')
    closeDrawer();
    emit('success');
  } finally {
    setDrawerProps({confirmLoading: false});
  }
}
</script>

<style lang="less">
  @prefix-cls: ~'@{namespace}-role-api-perm';
  .@{prefix-cls} {
    &-action-type {
      margin: 5px;
  

      .ant-select-single {
        width: 110px !important;
      }
    }
  }

  .ant-transfer .ant-transfer-operation .ant-btn {
    .anticon {
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
</style>
